const router = require('koa-router')();
const {
    numberFromCtx,
    stringFromCtx,
    formatErrorJson,
    formatSuccessJson
} = require('../../../../utils/retUtil');
const CONST = require('../../../../utils/const');
const api4back = require('../../../../service/api4back');

router.prefix('/promoter/users');

router.get('/', async (ctx, next) => {
    await ctx.render('index', {
        title: 'Hello Koa 2! by yjx/v1/promoter/users'
    })
});

/**
 * 获取推广方信息
 * @author 李强
 * @date 2018-07-3
 *
 * 参数：device
 */
const getPromoterInfo = async (ctx, next) => {
    //获取参数
    const userId = numberFromCtx(ctx, 'userId');
    //参数判断
    if(!userId){
        throw new Error("用户唯一标识无效");
    }
    //数据请求
    const para = {userId:userId};
    ctx.body = formatSuccessJson(await api4back.getPromoterInfo(para));

};
router.get('/getPromoterInfo', getPromoterInfo);
router.post('/getPromoterInfo', getPromoterInfo);



/**
 * 获取手机号验证码
 * @author 李强
 * @date 2018-07-3
 *
 * 参数：mobile : 用户手机号, 验证规则可放宽, 仅限制1开头, 11位纯数字即可
 * 参数：zone : 国际区号, 暂时支持国内, 固定传 +86
 * 参数：type : 验证码类型, 暂定如下:1 短信验证码
 2 语音验证码
 暂时固定为1
 */
const getBackMobileVerCode = async (ctx, next) => {
    //获取参数
    const mobile = stringFromCtx(ctx, 'mobile');
    const zone = "+86";
    const type = 1;
    //参数判断
    if (!mobile) {
        throw new Error('手机号错误');
    }
    //数据请求
    const para = {mobile: mobile, zone: zone, type: type};
    ctx.body = formatSuccessJson(await api4back.getBackMobileVerCode(para));

};
router.get('/getBackMobileVerCode', getBackMobileVerCode);
router.post('/getBackMobileVerCode', getBackMobileVerCode);




/**
 * 验证验证码
 * @author 李强
 * @date 2018-07-3
 *
 * 参数：mobile : 用户手机号, 验证规则可放宽, 仅限制1开头, 11位纯数字即可
 * 参数：zone : 国际区号, 暂时支持国内, 固定传 +86
 * 参数：verCode : 六位验证码
 2 语音验证码
 暂时固定为1
 */
const checkBalkMobileCode = async (ctx, next) => {
    //获取参数
    const mobile = numberFromCtx(ctx, 'mobile');
    const zone = "+86";
    const verCode = stringFromCtx(ctx, 'captcha');
    //参数判断
    if(!mobile && !verCode){
        throw new Error("手机号或验证码有误");
    }
    //数据请求
    const para = {mobile:mobile, zone:zone, verCode:verCode};
    const userInfo = await api4back.checkBalkMobileCode(para);
    ctx.session[CONST.SESSION_USER] = userInfo;
    ctx.body = formatSuccessJson(userInfo);
};
router.get('/checkBalkMobileCode', checkBalkMobileCode);
router.post('/checkBalkMobileCode', checkBalkMobileCode);



/**
 * 获取用户详细信息
 * @author 李强
 * @date 2018-07-3
 */
const getUserInfo = async (ctx, next) => {
    const userInfo = ctx.session[CONST.SESSION_USER];
    if(!userInfo){
        throw new Error('无权限');
    }
    ctx.body = formatSuccessJson(userInfo);
};
router.get('/getUserInfo', getUserInfo);
router.post('/getUserInfo', getUserInfo);

module.exports = router;
